# class AsyncRedis:
#
#     def __init__(self, host, port, loop):
#         self.host = host
#         self.port = port
#         self.loop = loop
#         self.separator = "\r\n".encode()
#
#     async def connect(self):
#         reader, writer = await asyncio.open_connection(self.host, self.port, loop=self.loop)
#         self.reader = reader
#         self.writer = writer
#
#     def format_command(self, commands):
#         length = len(commands)
#         command = "*{}\r\n".format(length)
#         for v in commands:
#             bytes = v.encode("utf-8")
#             bytes_length = len(bytes)
#             sub_command = "${}\r\n".format(bytes_length) + "{}\r\n".format(v)
#             command += sub_command
#         print(command)
#         return command
#
#     def execute_command(self, command):
#         self.writer.write(command.encode("utf-8"))
#
#     async def set(self, key, value):
#         command = self.format_command(["SET", key, value])
#         self.execute_command(command)
#         ret, error = await self.wait_ret()
#         print(ret)
#         return ret
#
#     async def hset(self, hash_key, key, value):
#         command = self.format_command(["HSET", hash_key, key, value])
#         self.execute_command(command)
#
#     async def get(self, key):
#         command = self.format_command(['GET', key])
#         self.execute_command(command)
#         ret = await self.wait_ret()
#         return ret
#
#     async def wait_ret(self):
#         ret = await self.reader.readuntil(self.separator)
#         ret = ret.decode()
#         mark = ret[0:1]
#         if mark == "$":
#             pos = ret.index("\r\n")
#             ret = ret[1:pos]
#             ret = await self.reader.read(int(ret))
#             ret = ret.decode()
#             return ret, True
#         elif mark == "+":
#             pos = ret.index("\r\n")
#             ret = ret[1:pos]
#             return ret, True
#         elif mark == "-":
#             pos = ret.index("\r\n")
#             ret = ret[1:pos]
#             return ret, False
#
#     async def close(self):
#         self.writer.close()
#
# import asyncio
#
# async def NewRedis(loop):
#     redis = AsyncRedis("127.0.0.1", 6379, loop)
#     await redis.connect()
#     # await redis.get("name")
#     await redis.set("name", "云想衣裳花想容，春风拂槛露华浓。若非群玉山头见，会向瑶台月下逢。")
# loop = asyncio.get_event_loop()
# loop.run_until_complete(NewRedis(loop))
# loop.close()


import redis

import redis


class MyRedis():
    def __init__(self, ip='127.0.0.1', password=None, port=6379, db=1):  # 构造函数
        try:
            self.r = redis.Redis(
                host=ip,
                password=password,
                port=port,
                db=db)  # 连接redis固定方法,这里的值必须固定写死
        except Exception as e:
            print('redis连接失败，错误信息%s' % e)

    def str_get(self, k):
        res = self.r.get(k)   # 会从服务器传对应的值过来，性能慢
        if res:
            return res.decode()   # 从redis里面拿到的是bytes类型的数据，需要转换一下

    def str_set(self, k, v):  # time默认失效时间
        self.r.set(k, v)

    def str_expire(self, k, time):
        self.r.expire(k, time)

    def delete(self, k):
        tag = self.r.exists(k)
        #  判断这个key是否存在,相对于get到这个key他只是传回一个存在火灾不存在的信息，
        # 而不用将整个k值传过来（如果k里面存的东西比较多，那么传输很耗时）
        if tag:
            self.r.delete(k)
        else:
            print('这个key不存在')

    def hash_get(self, name, k):  # 哈希类型存储的是多层字典（嵌套字典）
        res = self.r.hget(name, k)
        if res:
            return res.decode()  # 因为get不到值得话也不会报错所以需要判断一下

    def hash_set(self, name, k, v):  # 哈希类型的是多层
        self.r.hset(name, k, v)   # set也不会报错

    def hash_getall(self, name):
        res = self.r.hgetall(name)   # 得到的是字典类型的，里面的k,v都是bytes类型的
        data = {}
        if res:
            for k, v in res.items():  # 循环取出字典里面的k,v，在进行decode
                k = k.decode()
                v = v.decode()
                data[k] = v
        return data

    def hash_del(self, name, k):
        res = self.r.hdel(name, k)
        if res:
            print('删除成功')
            return True
        else:
            print('删除失败，该key不存在')
            return False

    @property
    # 属性方法，
    # 使用的时候和变量一个用法就好比实例，A=MyRedis(), A.clean_redis使用，
    # 如果不加这个@property,使用时A=MyRedis(), A.clean_redis()   后面需要加这个函数的括号
    def clean_redis(self):
        self.r.flushdb()   # 清空 redis
        print('清空redis成功！')
        return False


if __name__ == "__main__":
    my = MyRedis('127.0.0.1')
    # my.str_set('time_1','1254845122')
    # my.hash_set('h_time','name','lily')
    # print('h_time:',my.hash_getall('h_time'))
    # my.clean_redis
    my.r.set('time2', '123143242')
    my.r.expire('time2', 30)
